package com.endpoint.memory;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.scheduling.annotation.Scheduled;

/**
 * Description: 内存收集器
 *
 * @author yuanma
 * @version 1.0
 * @date: 2018/7/20 15:14
 * @since JDK 1.8
 */
public class MemCollector {

	private static final int MAX_SIZE = 5;

	private List<MemStatus> status;

	public MemCollector(List<MemStatus> status) {
		this.status = status;
	}

	@Scheduled(cron = "0/5 * *  * * ? ")
    public void collect() {
        Runtime runtime = Runtime.getRuntime();
        Long maxMemory = runtime.maxMemory();
        Long totalMemory = runtime.totalMemory();
        Map<String, Object> memoryMap = new HashMap<>(2, 1);
        Date date = Calendar.getInstance().getTime();
        memoryMap.put("maxMemory", maxMemory);
        memoryMap.put("totalMemory", totalMemory);
        if (status.size() > MAX_SIZE) {
            status.remove(0);
            status.add(new MemStatus(date, memoryMap));
        } else {
            status.add(new MemStatus(date, memoryMap));
        }
    }

}
